package com.cmii.sjw.department.control.jsc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cmii.sjw.department.control.jsc.mapper.ProfessionDetailMapper;
import com.cmii.sjw.department.control.jsc.mapper.QualificationTeacherMapper;
import com.cmii.sjw.department.control.jsc.model.ProfessionDetail;
import com.cmii.sjw.department.control.jsc.model.QualificationTeacher;
import com.cmii.sjw.department.control.jsc.service.TeacherService;
import com.cmii.sjw.department.control.jsc.util.Result;
import com.cmii.sjw.department.control.jsc.vo.TeacherVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Slf4j
@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private  QualificationTeacherMapper qualificationTeacherMapper;
    @Autowired
    private  ProfessionDetailMapper professionDetailMapper;

    @Override
    public Result<TeacherVO> listGroupedByTeacher(String schoolName) {
        if (!StringUtils.hasText(schoolName)) {
            return Result.error("高校名称不能为空");
        }

        TeacherVO vo = new TeacherVO();

        // 查博士研究生学历占比
        LambdaQueryWrapper<QualificationTeacher> qualificationWrapper = new LambdaQueryWrapper<>();
        qualificationWrapper.eq(QualificationTeacher::getSchoolName, schoolName)
                            .eq(QualificationTeacher::getType, "高校")
                            .eq(QualificationTeacher::getName, "博士研究生")
                            .eq(QualificationTeacher::getIsDeleted, 0);

        QualificationTeacher qualification = qualificationTeacherMapper.selectOne(qualificationWrapper);
        if (qualification != null && StringUtils.hasText(qualification.getPercentage())) {
            vo.setQualificationPercentage(parsePercent(qualification.getPercentage()));
        }

        // 查双师型占比
        LambdaQueryWrapper<ProfessionDetail> professionWrapper = new LambdaQueryWrapper<>();
        professionWrapper.eq(ProfessionDetail::getName, schoolName)
                         .eq(ProfessionDetail::getIsDeleted, 0);

        ProfessionDetail profession = professionDetailMapper.selectOne(professionWrapper);
        if (profession != null && StringUtils.hasText(profession.getPercent())) {
            vo.setProfessionPercent(parsePercent(profession.getPercent()));
        }

        return Result.success(vo);
    }

    private BigDecimal parsePercent(String percentStr) {
        try {
            String clean = percentStr.replace("%", "").trim();
            return new BigDecimal(clean).divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
        } catch (Exception e) {
            log.warn("百分比转换失败：{}", percentStr);
            return BigDecimal.ZERO;
        }
    }
}